<template>
  <a-modal
    :title="'上传汇总单 - ' + orderNo"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleUploadOk"
    @cancel="handleCancel"
    :width="600">
    
    <a-form-model ref="form" :model="form">
      <a-alert
        v-if="validateMessage.show"
        :message="validateMessage.message"
        :type="validateMessage.type"
        :showIcon="true"
        style="margin-bottom: 20px" />
        
      <div class="upload-container">
        <a-upload
          name="file"
          :multiple="false"
          :fileList="fileList"
          :beforeUpload="beforeUpload"
          :remove="handleRemove"
          :showUploadList="{ showPreviewIcon: false }">
          <a-button>
            <a-icon type="upload" /> 选择汇总单文件
          </a-button>
          <div class="ant-upload-hint" style="margin-top: 10px">
            请选择Excel格式的汇总单文件
          </div>
        </a-upload>
        
        <div class="validate-container" v-if="fileList.length > 0">
          <a-button type="primary" @click="validateExcelFile" :loading="validating">
            <a-icon type="check-circle" /> 验证文件
          </a-button>
        </div>
        
        <div class="result-container" v-if="parseResult && parseResult.success">
          <div class="result-title">解析结果：</div>
          <div class="result-content">
            <div class="result-item">
              <span class="label">订单号：</span>
              <span class="value">{{ parseResult.orderNo }}</span>
            </div>
            <div class="result-item">
              <span class="label">型材数量：</span>
              <span class="value">{{ parseResult.profileCount }} 条</span>
            </div>
            <div class="result-item">
              <span class="label">玻璃数量：</span>
              <span class="value">{{ parseResult.glassCount }} 条</span>
            </div>
            <div class="result-item">
              <span class="label">配件数量：</span>
              <span class="value">{{ parseResult.accessoriesCount }} 条</span>
            </div>
          </div>
        </div>
      </div>
    </a-form-model>
  </a-modal>
</template>

<script>
import { postAction } from '@/api/manage'
import { 
  validateSummaryFile, 
  processSummaryFileResult 
} from '@/api/oms/designFile'

export default {
  name: 'UploadSummaryModal',
  props: {
    orderId: {
      type: String,
      required: true
    },
    orderNo: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      validating: false,
      form: {},
      fileList: [],
      file: null,
      validateMessage: {
        show: false,
        message: '',
        type: 'info'
      },
      parseResult: null,
      orderNoMatched: false
    }
  },
  methods: {
    show() {
      this.visible = true
      this.reset()
    },
    reset() {
      this.form = {}
      this.fileList = []
      this.file = null
      this.validateMessage = {
        show: false,
        message: '',
        type: 'info'
      }
      this.parseResult = null
      this.orderNoMatched = false
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    beforeUpload(file) {
      // 检查文件类型
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      file.type === 'application/vnd.ms-excel'
      
      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过20MB!')
        return false
      }
      
      this.fileList = [file]
      this.file = file
      this.validateMessage = {
        show: true,
        message: '请点击验证按钮验证文件内容',
        type: 'warning'
      }
      
      // 返回false，阻止默认上传行为
      return false
    },
    handleRemove() {
      this.fileList = []
      this.file = null
      this.validateMessage = {
        show: false,
        message: '',
        type: 'info'
      }
      this.parseResult = null
      this.orderNoMatched = false
      return true
    },
    validateExcelFile() {
      if (!this.file) {
        this.$message.warning('请先选择汇总单文件')
        return
      }
      
      this.validating = true
      this.validateMessage = {
        show: true,
        message: '正在验证文件，请稍候...',
        type: 'info'
      }
      
      const formData = new FormData()
      formData.append('file', this.file)
      formData.append('orderId', this.orderId)
      
      validateSummaryFile(formData)
        .then(res => {
          if (res.success) {
            this.parseResult = res.result
            
            // 检查订单号是否匹配
            if (this.parseResult && this.parseResult.orderNo) {
              this.orderNoMatched = this.parseResult.orderNo === this.orderNo
              
              if (this.orderNoMatched) {
                this.validateMessage = {
                  show: true,
                  message: '验证成功，汇总单与订单匹配',
                  type: 'success'
                }
              } else {
                this.validateMessage = {
                  show: true,
                  message: `验证失败，汇总单订单号(${this.parseResult.orderNo})与当前订单号(${this.orderNo})不匹配`,
                  type: 'error'
                }
              }
            } else {
              this.validateMessage = {
                show: true,
                message: '验证失败，未能从文件中识别出订单号',
                type: 'error'
              }
            }
          } else {
            this.validateMessage = {
              show: true,
              message: '验证失败: ' + (res.message || '未知错误'),
              type: 'error'
            }
          }
        })
        .catch(error => {
          console.error('验证文件出错', error)
          this.validateMessage = {
            show: true,
            message: '验证文件过程中发生错误',
            type: 'error'
          }
        })
        .finally(() => {
          this.validating = false
        })
    },
    handleUploadOk() {
      if (!this.file) {
        this.$message.warning('请先选择汇总单文件')
        return
      }
      
      // 如果文件未验证或验证不通过，提示先验证
      if (!this.parseResult || !this.orderNoMatched) {
        this.$message.warning('请先验证文件，并确保订单号匹配')
        return
      }
      
      this.confirmLoading = true
      const formData = new FormData()
      formData.append('file', this.file)
      formData.append('orderId', this.orderId)
      formData.append('parseResult', JSON.stringify(this.parseResult))
      
      // 调用保存解析结果的接口
      processSummaryFileResult(formData)
        .then(res => {
          if (res.success) {
            // 显示更详细的成功信息
            this.$notification.success({
              message: '上传成功',
              description: `汇总单已成功上传，订单${this.orderNo}状态已更新为"已上传汇总单"`,
              duration: 4
            })
            
            // 关闭弹窗并触发成功事件
            this.visible = false
            this.$emit('upload-success')
          } else {
            this.$message.error(res.message || '保存解析结果失败')
          }
        })
        .catch(() => {
          this.$message.error('保存解析结果过程中发生错误')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleCancel() {
      this.visible = false
      this.reset()
    }
  }
}
</script>

<style scoped>
.upload-container {
  padding: 10px;
}

.validate-container {
  margin-top: 20px;
  border-top: 1px dashed #d9d9d9;
  padding-top: 20px;
}

.result-container {
  margin-top: 16px;
  background-color: #f5f5f5;
  padding: 10px 16px;
  border-radius: 4px;
}

.result-item {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.result-item .label {
  font-weight: bold;
  width: 80px;
  margin-right: 10px;
}

.result-item .value {
  flex: 1;
}

.result-item .value.match {
  color: #52c41a;
  font-weight: bold;
}

.ant-upload-hint {
  color: rgba(0, 0, 0, 0.45);
}
</style> 